﻿using Domain.Material_Management;
using Domain.Production_Modules;
using Domain.QualityInspection_Modelling;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.QualityInspection_ModCom;
using MES.Server.API.Dto.QualityInspection_DTO;
using ReturnValue;

namespace MES.Server.API.Application.Handler.QualityInspection_ModHandler.NewQualityInspectionCommandHandler
{
    public class UpdateQualityInspectionHandlers : IRequestHandler<UpdateQualityInspectionCommands, ApiResult<QualityInspectionDto>>
    {
        private readonly IRepository<QualityInspection> _qualityRepo;
        private readonly IRepository<ProduceModel> _produceRepo;
        private readonly IRepository<MaterialGroupModel> _materialGroupRepo;

        public UpdateQualityInspectionHandlers(
            IRepository<QualityInspection> qualityRepo,
            IRepository<ProduceModel> produceRepo,
            IRepository<MaterialGroupModel> materialGroupRepo)
        {
            _qualityRepo = qualityRepo;
            _produceRepo = produceRepo;
            _materialGroupRepo = materialGroupRepo;
        }

        public async Task<ApiResult<QualityInspectionDto>> Handle(UpdateQualityInspectionCommands request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<QualityInspectionDto>();
            var updateDto = request.Dto;

            var inspection = await _qualityRepo.GetValue(updateDto.Id);
            if (inspection == null)
                return result.Fail("质检记录不存在");

            var newProduction = await _produceRepo.GetValue(updateDto.ProductionOrderId);
            if (newProduction == null)
                return result.Fail("新关联的生产工单不存在");
            if (newProduction.ProduceNum != newProduction.FinishProduceNum)
                return result.Fail("仅允许关联生产完成率100%的工单");

            var newMaterialGroup = await _materialGroupRepo.GetValue(newProduction.MaterialGroupId);
            if (newMaterialGroup == null)
                return result.Fail("新关联工单的物料群组不存在");

            if (updateDto.QualifiedQuantity < 0 || updateDto.QualifiedQuantity > newProduction.ProduceNum)
                return result.Fail($"合格数量必须在0到{newProduction.ProduceNum}之间");

            inspection.ProductionOrderId = updateDto.ProductionOrderId;
            inspection.MaterialGroupId = newProduction.MaterialGroupId;
            inspection.QualifiedQuantity = updateDto.QualifiedQuantity;
            inspection.UnqualifiedQuantity = newProduction.ProduceNum - updateDto.QualifiedQuantity;
            inspection.Inspector = updateDto.Inspector;
            inspection.InspectionTime = DateTime.Now;

            var dbResult = await _qualityRepo.UpdateAsync(inspection);
            if (dbResult <= 0)
                return result.Fail("质检记录更新失败");

            var responseDto = new QualityInspectionDto
            {
                Id = inspection.Id,
                InspectionNumber = inspection.InspectionNumber,
                ProductionOrderId = inspection.ProductionOrderId,
                ProductionOrderName = newProduction.ProduceName,
                MaterialGroupId = inspection.MaterialGroupId,
                MaterialGroupName = newMaterialGroup.MaterialGroupName,
                InspectedQuantity = newProduction.ProduceNum,
                QualifiedQuantity = inspection.QualifiedQuantity,
                UnqualifiedQuantity = inspection.UnqualifiedQuantity,
                QualificationRate = (decimal)inspection.QualifiedQuantity / newProduction.ProduceNum * 100,
                Inspector = inspection.Inspector,
                InspectionTime = inspection.InspectionTime
            };

            return result.Success("质检记录更新成功", responseDto);
        }
    }
}
